package com.bmob.lover.ui.fragment.cost

import android.app.DatePickerDialog
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.DatePicker
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.qmuiteam.qmui.skin.QMUISkinHelper
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction
import com.theone.common.constant.BundleConstant
import com.theone.common.ext.*
import com.theone.common.util.filter.MoneyValueFilter
import com.theone.common.widget.datePicker.DateTimePicker
import com.bmob.lover.R
import com.bmob.lover.app.ext.pointer
import com.bmob.lover.data.constant.CostConstant
import com.bmob.lover.data.model.bean.BmobDate
import com.bmob.lover.data.model.bean.Cost
import com.bmob.lover.data.model.bean.CostCategory
import com.bmob.lover.databinding.FragmentCostAddBinding
import com.bmob.lover.ui.adapter.CostCategorySelectAdapter
import com.bmob.lover.ui.fragment.base.BaseFragment
import com.bmob.lover.viewmodel.request.CostCategoryRequestViewModel
import com.bmob.lover.viewmodel.request.CostCategoryUpdateViewModel
import com.bmob.lover.viewmodel.request.CostSaveRequestViewModel
import com.bmob.lover.viewmodel.state.CostAddViewModel
import com.theone.mvvm.core.app.ext.*
import com.theone.mvvm.ext.qmui.*
import java.util.*

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-05-19 11:13
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
class CostAddItemFragment private constructor() :
    BaseFragment<CostAddViewModel, FragmentCostAddBinding>(),
    DateTimePicker.ResultHandler, DatePickerDialog.OnDateSetListener {

    companion object {
        fun newInstance(type: Int = -1, bean: Cost? = null): CostAddItemFragment {
            return CostAddItemFragment().apply {
                arguments = Bundle().apply {
                    bean?.let {
                        putParcelable(BundleConstant.DATA, it)
                    }
                    putInt(BundleConstant.TYPE, type)
                }
            }
        }
    }

    private val mCost: Cost? by getValue(BundleConstant.DATA)
    private var mType: Int = -1

    private val mCategoryRequest: CostCategoryRequestViewModel by viewModels()
    private val mCategoryUpdateRequest: CostCategoryUpdateViewModel by viewModels()
    private val mCostSaveRequest: CostSaveRequestViewModel by viewModels()

    private val mCategoryAdapter: CostCategorySelectAdapter by lazy {
        CostCategorySelectAdapter().apply {
            setOnItemClickListener { adapter, view, position ->
                mSelect = position
            }
            animationEnable = false
        }
    }

    private val mDatePicker: DateTimePicker by lazy {
        DateTimePicker(
            mActivity,
            this,
            getNearestMonthDate(-6),
            Date(),
            DateTimePicker.Builder(mActivity).apply {
                setOk("确定")
                setOk("确定")
                setCancel("取消")
                setCancelTextColor(Color.RED)
                setOkTextColor(getColor(mActivity, R.color.qmui_config_color_blue))
                setTitleTextColor(getColor(mActivity, R.color.qmui_config_color_gray_3))
                setKeepLastSelected(false)
                setSelectedTextColor(
                    QMUISkinHelper.getSkinColor(
                        getContentView(),
                        R.attr.app_skin_primary_color
                    )
                )
                setShowType(DateTimePicker.ShowType.MINUTE)
            })
    }

    override fun initView(root: View) {
        with(getDataBinding()) {
            etMoney.filters = arrayOf(MoneyValueFilter())
            recyclerView.init(LinearLayoutManager(mActivity,LinearLayoutManager.HORIZONTAL,false),mCategoryAdapter)
        }

        mCost.notNull({
            mType = it.type
            setTitleWitchBackBtn(CostConstant.COST_TYPES[mType])
            getTopBar()?.addRightTextButton("删除", R.id.topbar_right_text)
                ?.setOnClickListener { view ->
                    showDeleteCostDialog(it)
                }
            with(getViewModel()) {
                date.set(it.date.iso)
                remark.set(it.remark)
                money.set(it.money.regularizePrice())
            }
        }, {
            mType = requireArguments().getInt(BundleConstant.TYPE)
        })
        getViewModel().categoryType.set(CostConstant.getCostCategoryType(mType))
        mCategoryRequest.type = mType
        getContentView().post {
            showLoadingPage()
        }
    }

    override fun onLazyInit() {
        mCategoryRequest.requestServer()
    }

    override fun onPageReLoad() {
        showLoadingPage()
        onLazyInit()
    }

    override fun createObserver() {
        addLoadingObserve(mCostSaveRequest, mCategoryUpdateRequest)
        addFailTipsObserve(mCategoryUpdateRequest,mCostSaveRequest)
        mCategoryRequest.run {
            getResponseLiveData().observe(this@CostAddItemFragment) {
                setCostCategoryLabelsData(it)
                showSuccessPage()
            }
            getErrorLiveData().observe(this@CostAddItemFragment) {
                showErrorPage(it)
            }
        }

        mCostSaveRequest.run {
            getObjectSuccessLiveDate().observe(this@CostAddItemFragment) {
                mEventVm.onPublishSuccess("$mTableName${this@CostAddItemFragment.mType}")
                showSuccessTipsExitDialog(it.msg)
            }
        }
        mEventVm.getPublishLiveData().observe(this) {
            if (it == getViewModel().categoryType.get()) {
                requestCategoryNewData()
            }
        }
        mCategoryUpdateRequest.getObjectSuccessLiveDate().observe(this) {
            showSuccessTipsDialog(it.msg)
            requestCategoryNewData()
        }
    }

    /**
     * 请求新的分类数据
     */
    private fun requestCategoryNewData() {
        mCategoryRequest.isFirst = false
        mCategoryRequest.isFresh = true
        mCategoryRequest.requestServer()
    }

    private fun setCostCategoryLabelsData(list: List<CostCategory>) {
        mCategoryAdapter.setList(list)
        getDataBinding().run {
            tvModify.visible(list.isNotEmpty())
            mCost?.let {
                for ((index, data) in list.withIndex()) {
                    if (data.objectId == it.category.objectId) {
                        recyclerView.scrollToPosition(index)
                        mCategoryAdapter.mSelect = index
                        break
                    }
                }
            }
        }
    }

    private fun showDeleteCostDialog(cost: Cost) {
        context?.showMsgDialog(
            "提示",
            "是否删除该条记录",
            listener = QMUIDialogAction.ActionListener { dialog, index ->
                dialog?.dismiss()
                if (index > 0) {
                    mCostSaveRequest.delete(cost)
                }
            },
            prop = QMUIDialogAction.ACTION_PROP_NEGATIVE
        )
    }

    override fun getBindingClick() = ProxyClick()

    inner class ProxyClick  {

        fun saveOrUpdate() {
            when {
                getViewModel().money.get().isEmpty() -> showFailTipsDialog("请填写金额")
                else -> {
                    val date = BmobDate(getViewModel().date.get().formatDate(YYYY_MM_DD_HH_MM))
                    val money = getViewModel().money.get().toDouble()
                    val remark = getViewModel().remark.get()
                    val category = mCategoryAdapter.data[mCategoryAdapter.mSelect].pointer()
                    mCost.notNull({
                        it.category = category
                        it.money = money
                        it.remark = remark
                        it.date = date
                        mCostSaveRequest.update(it)
                    }, {
                        mCostSaveRequest.save(mType, money, category, date, remark)
                    })
                }
            }
        }

        fun editCategory() {
            startFragment(CostCategoryFragment.newInstance(mType))
        }

        fun addCategory() {
            context?.showEditDialog(
                "添加类别",
                hint = "类别名称",
                listener = object : QMUIEditDialogListener {
                    override fun onEditDialogClick(
                        dialog: QMUIDialog,
                        content: String,
                        index: Int
                    ) {
                        dialog.dismiss()
                        val name = content.trimAll()
                        if (index > 0 && name.isNotEmpty()) {
                            if (content.length > 4) {
                                showFailTipsDialog("类别名称不能超过四个字")
                            } else {
                                mCategoryRequest.getResponseLiveData().value?.let {
                                    for (item in it) {
                                        if (item.name == name) {
                                            showFailTipsDialog("类别已存在")
                                            return
                                        }
                                    }
                                    mCategoryUpdateRequest.create(mType, name, it.size + 1)
                                }

                            }
                        }
                    }
                })
        }

        fun selectDate() {
            mDatePicker.show(getViewModel().date.get().formatDate(YYYY_MM_DD_HH_MM))
        }

    }

    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        getViewModel().date.set("$year-${month + 1}-$dayOfMonth 00-00")
    }

    override fun handle(date: Date?) {
        getViewModel().date.set(date?.formatString(YYYY_MM_DD_HH_MM))
    }

}